<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者名称" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入患者名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="医生名称" prop="doctorName">
        <el-input v-model="queryParams.doctorName" placeholder="请输入医生名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="就诊日期" prop="appointmentDate">
        <el-date-picker clearable v-model="queryParams.appointmentDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择就诊日期" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['appointments:appointments:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['appointments:appointments:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['appointments:appointments:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['appointments:appointments:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格列表 -->
    <el-table v-loading="loading" :data="appointmentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="患者名称" align="center" prop="patientName" />
      <el-table-column label="身份证号" align="center" prop="idCard">
        <template slot-scope="scope">
          <span>{{ desensitizeIdCard(scope.row.idCard) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生名称" align="center" prop="doctorName" />
      <el-table-column label="医院名称" align="center" prop="hospitalName" />
      <el-table-column label="科室名称" align="center" prop="deptName" />
      <el-table-column label="就诊日期" align="center" prop="appointmentDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.appointmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊时段" align="center" prop="timeSlot">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.time_slot" :value="scope.row.timeSlot" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['appointments:appointments:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['appointments:appointments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改预约信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者名称" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者名称" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>

        <!-- 三级联动选择 -->
        <el-form-item label="医院名称" prop="hospitalName">
          <el-select v-model="form.hospitalId" placeholder="请选择医院" @change="loadDepartments" clearable>
            <el-option v-for="hospital in hospitalsList" :key="hospital.hospitalId" :label="hospital.hospitalName" :value="hospital.hospitalId" />
          </el-select>
        </el-form-item>

        <el-form-item label="科室名称" prop="deptName">
          <el-select v-model="form.deptId" placeholder="请选择科室" @change="loadDoctors" :disabled="!form.hospitalId" clearable>
            <el-option v-for="dept in departments" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
          </el-select>
        </el-form-item>

        <!-- 预约逻辑选择 -->
        <el-form-item label="预约逻辑">
          <el-radio-group v-model="appointmentLogic" @change="switchAppointmentLogic">
            <el-radio label="1">先选医生，再选时间</el-radio>
            <el-radio label="2">先选时间，再选医生</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 先选医生，再选时间 -->
        <template v-if="appointmentLogic === '1'">
          <el-form-item label="医生名称" prop="doctorName">
            <el-select v-model="form.doctorId" placeholder="请选择医生" @change="loadAvailableTimeSlots" :disabled="!form.deptId" clearable>
              <el-option v-for="doctor in doctors" :key="doctor.doctorId" :label="doctor.doctorName" :value="doctor.doctorId" />
            </el-select>
          </el-form-item>

          <el-form-item label="就诊日期" prop="appointmentDate">
            <el-date-picker
              v-model="form.appointmentDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择就诊日期"
              @change="loadAvailableTimeSlots"
              :disabled="!form.doctorId">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="就诊时段" prop="timeSlot">
            <el-select
              v-model="form.timeSlot"
              placeholder="请选择就诊时段"
              :disabled="!form.appointmentDate"
              clearable>
              <el-option v-for="slot in availableTimeSlots" :key="slot" :label="slot" :value="slot" />
            </el-select>
          </el-form-item>
        </template>

        <!-- 先选时间，再选医生 -->
        <template v-if="appointmentLogic === '2'">
          <el-form-item label="就诊日期" prop="appointmentDate">
            <el-date-picker
              v-model="form.appointmentDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择就诊日期"
              @change="handleDateChange"
              :disabled="!form.deptId">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="就诊时段" prop="timeSlot">
            <el-select
              v-model="form.timeSlot"
              placeholder="请选择就诊时段"
              @change="loadAvailableDoctors"
              :disabled="!form.appointmentDate"
              clearable>
              <el-option v-for="slot in timeSlots" :key="slot.value" :label="slot.label" :value="slot.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="医生名称" prop="doctorId">
            <el-select
              v-model="form.doctorId"
              placeholder="请选择医生"
              :disabled="!form.timeSlot"
              clearable>
              <el-option v-for="doctor in availableDoctors" :key="doctor.doctorId" :label="doctor.doctorName" :value="doctor.doctorId" />
            </el-select>
          </el-form-item>
        </template>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAppointments, getAppointments, delAppointments, addAppointments, updateAppointments } from "@/api/appointments/appointments";
import { listByDeptId, selectAvailableDoctors} from "@/api/doctors/doctors";
import { selectDeptByHospitalId } from "@/api/departments/departments";
import { getAllHospitals, } from "@/api/hospitals/hospitals";
import { getScheduleByDoctorAndDate } from "@/api/schedules/schedules";

export default {
  name: "Appointments",
  dicts: ["time_slot"],
  data() {
    return {
      // 数据列表
      hospitalsList: [],  // 所有医院列表
      departments: [],    // 当前医院下的科室列表
      doctors: [],        // 当前科室下的医生列表

      // 预约数据
      availableTimeSlots: [],  // 可用时段列表
      availableDoctors: [],    // 可用医生列表
      appointmentLogic: "1",   // 预约逻辑模式：1-先选医生 2-先选时间

      // 状态管理
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,

      // 表格数据
      appointmentsList: [],

      // 对话框数据
      title: "",
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        patientName: null,
        doctorName: null,
        appointmentDate: null
      },

      // 表单数据
      form: {
        appointmentId: null,
        patientName: null,
        idCard: null,
        doctorId: null,
        hospitalId: null,
        deptId: null,
        timeSlot: null,
        appointmentDate: null
      },

      // 表单校验
      rules: {
        patientName: [{ required: true, message: "患者名称不能为空", trigger: "blur" }],
        idCard: [{ required: true, message: "身份证号不能为空", trigger: "blur" }],
        timeSlot: [{ required: true, message: "就诊时段不能为空", trigger: "change" }],
        hospitalId: [{ required: true, message: "医院名称不能为空", trigger: "change" }],
        deptId: [{ required: true, message: "科室名称不能为空", trigger: "change" }],
        doctorId: [{ required: true, message: "医生名称不能为空", trigger: "change" }],
        appointmentDate: [{ required: true, message: "就诊日期不能为空", trigger: "change" }]
      },

      // 时段选项
      timeSlots: [
        { value: "上午", label: "上午" },
        { value: "下午", label: "下午" },
        { value: "夜间", label: "夜间" }
      ]
    };
  },

  created() {
    this.getList();
    this.loadHospitals();
  },

  methods: {
    // 表格数据操作
    getList() {
      this.loading = true;
      listAppointments(this.queryParams).then(response => {
        this.appointmentsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 表单操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预约信息";
    },

    handleUpdate(row) {
      this.reset();
      const appointmentId = row ? row.appointmentId : this.ids[0];
      getAppointments(appointmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预约信息";
        this.loadDepartments();
      });
    },

    handleDelete(row) {
      const appointmentIds = row ? [row.appointmentId] : this.ids;
      this.$modal.confirm('是否确认删除选中的预约信息？').then(() => {
        return delAppointments(appointmentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 身份证号验证
          if (!this.validateIdCard(this.form.idCard)) {
            this.$modal.msgError('请输入正确的身份证号');
            return;
          }
          // 验证所选时段是否还有号源
          if (this.checkAvailability()) {
            const processSuccess = () => {
              this.$message.success(this.form.appointmentId ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            };

            if (this.form.appointmentId) {
              updateAppointments(this.form).then(processSuccess);
            } else {
              // 新增预约时减少对应时段的号源
              addAppointments(this.form).then(() => {
                this.updateQuota(-1); // -1 表示减少一个号源
                processSuccess();
              });
            }
          }
          const processSuccess = () => {
            this.$modal.msgSuccess(this.form.appointmentId ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          };

          if (this.form.appointmentId) {
            updateAppointments(this.form).then(processSuccess);
          } else {
            addAppointments(this.form).then(processSuccess);
          }
        }
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        appointmentId: null,
        patientName: null,
        idCard: null,
        doctorId: null,
        hospitalId: null,
        deptId: null,
        timeSlot: null,
        appointmentDate: null
      };
      this.resetForm("form");
      this.resetAppointmentData();
    },

    // 三级联动实现
    loadHospitals() {
      this.loading = true;
      getAllHospitals().then(response => {
        this.hospitalsList = response.data || [];
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error('获取医院列表失败:', error);
        this.$modal.msgError('获取医院列表失败');
      });
    },

    loadDepartments() {
      this.form.deptId = null;
      this.form.doctorId = null;
      this.departments = [];
      this.doctors = [];
      this.resetAppointmentData();

      if (this.form.hospitalId) {
        this.loading = true;
        selectDeptByHospitalId(this.form.hospitalId).then(response => {
          this.departments = response.data || [];
          this.loading = false;
        }).catch(error => {
          this.loading = false;
          console.error('获取科室列表失败:', error);
          this.$modal.msgError('获取科室列表失败');
        });
      }
    },

    loadDoctors() {
      this.form.doctorId = null;
      this.doctors = [];
      this.resetAppointmentData();

      if (this.form.deptId) {
        this.loading = true;
        listByDeptId(this.form.deptId).then(response => {
          this.doctors = response.data || [];
          this.loading = false;
        }).catch(error => {
          this.loading = false;
          console.error('获取医生列表失败:', error);
          this.$modal.msgError('获取医生列表失败');
        });
      }
    },

    // 预约逻辑切换
    switchAppointmentLogic() {
      this.resetAppointmentData();
    },

    resetAppointmentData() {
      this.availableTimeSlots = [];
      this.availableDoctors = [];

      if (this.appointmentLogic === "1") {
        this.form.timeSlot = null;
      } else {
        this.form.doctorId = null;
      }
    },
    // 添加日期格式化工具方法
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 先选医生模式下的操作
    loadAvailableTimeSlots() {
      if (this.form.doctorId && this.form.appointmentDate) {
        // 格式化日期为 yyyy-MM-dd 格式
        const formattedDate = this.formatDate(this.form.appointmentDate);
        console.log('准备获取排班信息，参数:', {
          doctorId: this.form.doctorId,
          appointmentDate: formattedDate // 确认有值
        });
        this.loading = true;
        getScheduleByDoctorAndDate(this.form.doctorId, formattedDate).then(response => {
          this.availableTimeSlots = [];
          const schedules = response.data || [];
          if (schedules.morningRemaining > 0) this.availableTimeSlots.push("上午");
          if (schedules.afternoonRemaining > 0) this.availableTimeSlots.push("下午");
          if (schedules.nightRemaining > 0) this.availableTimeSlots.push("夜间");

          this.loading = false;
        }).catch(error => {
          this.loading = false;
          console.error('获取医生排班信息失败:', error);
          this.$modal.msgError('获取医生排班信息失败');
        });
      }
    },

    // 先选时间模式下的操作
    handleDateChange() {
      if (this.appointmentLogic === "2") {
        this.form.timeSlot = null;
        this.availableDoctors = [];
      }
    },

    loadAvailableDoctors() {
      if (this.form.deptId && this.form.appointmentDate && this.form.timeSlot) {
        // 格式化日期为 yyyy-MM-dd 格式
        const formattedDate = this.formatDate(this.form.appointmentDate);
        console.log('准备获取医生信息，参数:', {
          deptId: this.form.deptId,
          appointmentDate: formattedDate ,
          timeSlot: this.form.timeSlot
        });
        this.loading = true;
        selectAvailableDoctors(this.form.deptId, formattedDate, this.form.timeSlot).then(response => {
          this.availableDoctors = response.data || [];
          this.loading = false;
        }).catch(error => {
          this.loading = false;
          console.error('获取可用医生失败:', error);
          this.$modal.msgError('获取可用医生失败');
        });
      }
    },
    // 检查所选时段是否还有号源
    checkAvailability() {
      if (this.appointmentLogic === "1") {
        // 先选医生模式
        if (!this.availableTimeSlots.includes(this.form.timeSlot)) {
          this.$message.error('所选时段已无号源');
          return false;
        }
      } else {
        // 先选时间模式
        if (!this.availableDoctors.some(d => d.doctorId === this.form.doctorId)) {
          this.$message.error('所选医生在此时段已无号源');
          return false;
        }
      }
      return true;
    },

    // 更新号源数量
    updateQuota(change) {
      updateQuota(
        this.form.doctorId,
        this.form.appointmentDate,
        this.form.timeSlot,
        change
      ).catch(error => {
        this.$message.error('更新号源失败，请重试');
      });
    },

    // 辅助方法
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appointmentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleExport() {
      this.download('appointments/appointments/export', { ...this.queryParams }, `appointments_${new Date().getTime()}.xlsx`);
    },

    desensitizeIdCard(idCard) {
      if (!idCard) return '';
      return idCard.replace(/(\d{4})\d{10}(\d{4})/, '$1********$2');
    },

    validateIdCard(idCard) {
      const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
      return reg.test(idCard);
    }
  }
}
</script>
